package com.shiroha.video.controller;

import com.mybatisflex.core.paginate.Page;
import com.shiroha.common.utils.PageResult;
import com.shiroha.common.utils.Result;
import com.shiroha.video.enums.WorkType;
import com.shiroha.video.pojo.dto.WorkDTO;
import com.shiroha.video.pojo.vo.ImageResponse;
import com.shiroha.video.pojo.vo.UploadWorkRequest;
import com.shiroha.video.pojo.vo.WorkVO;
import com.shiroha.video.service.IWorkImageService;
import com.shiroha.video.service.IWorkService;
import com.shiroha.video.service.IJellyfinService;
import lombok.AllArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtClaimAccessor;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;
import java.util.UUID;

@RestController
@RequestMapping("/vs/works")
@AllArgsConstructor
public class WorkController {
    private final IWorkService workService;
    private final IWorkImageService workImageService;
    private final IJellyfinService jellyfinService;

    /**
     * 分页查询作品
     * @param pageNum 页数
     * @param pageSize 页面大小
     * @return 分页结果
     */
    @GetMapping
    public PageResult<WorkVO> getWorksByPage(
            @AuthenticationPrincipal Jwt jwt,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "20") int pageSize
    ) {
        UUID userId = Optional.ofNullable(jwt)
                .map(JwtClaimAccessor::getSubject)
                .map(UUID::fromString)
                .orElse(null);
        Page<WorkVO> workVOPage = workService.selectWorksByPage(pageNum, pageSize, userId);
        return PageResult.<WorkVO>create()
                .setTotal(workVOPage.getTotalRow())
                .setTotalPage(workVOPage.getTotalPage())
                .setCurrentPage(pageNum)
                .setPageSize(pageSize)
                .setData(workVOPage.getRecords());
    }

    /**
     * 上传作品
     * @param jwt jwt认证对象
     * @param request 表单数据
     * @return 响应结果
     */
    @PostMapping
    public Result<String> uploadWork(@AuthenticationPrincipal Jwt jwt, @ModelAttribute UploadWorkRequest request) {
        WorkDTO workDTO = WorkDTO.create()
                .setAuthorId(UUID.fromString(jwt.getSubject()))
                .setTitle(request.getTitle())
                .setType(WorkType.fromValue(request.getWorkType()))
                .setTags(request.getTags())
                .setFiles(request.getFiles());

        workService.uploadWork(workDTO);
        return Result.success("上传成功");
    }

    /**
     * 获取图集作品的图片列表
     * @param workId 作品ID
     * @return 图片列表，包含访问的 URL 等信息
     */
    @GetMapping("/{workId}/images")
    public ImageResponse getWorkImages(@PathVariable Long workId) {
        return workImageService.getWorkImages(workId);
    }

    /**
     * 获取图集作品的图片
     * @param workId 作品ID
     * @param index 图像序号
     * @return 字节数组
     */
    @GetMapping("/{workId}/images/{index}")
    public ResponseEntity<byte[]> getWorkImageById(@PathVariable Long workId, @PathVariable int index) {
        byte[] bytes = workImageService.getWorkImageBytes(workId, index);
        return ResponseEntity.ok()
                .contentType(MediaType.IMAGE_JPEG)
                .body(bytes);
    }


    /**
     * 获取视频作品的预览图
     * @param itemId ItemId
     * @param tag 预览图Tag
     * @return 二进制数据
     */
    @GetMapping("/{itemId}/primary/{tag}")
    public ResponseEntity<byte[]> getWorkPrimaryByNum(@PathVariable("itemId") String itemId, @PathVariable String tag) {
        byte[] imageBytes = jellyfinService.getWorkPrimaryImage(itemId, tag);
        return ResponseEntity.ok()
                .contentType(MediaType.IMAGE_JPEG)
                .body(imageBytes);
    }
}
